package com.atguigu.gmall.activity.task;

import com.atguigu.gmall.activity.mapper.SecKillGoodsMapper;
import com.atguigu.gmall.activity.util.DateUtil;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 秒杀商品存入缓存的定时任务
 */
@Component
public class SeckillTask {

    @Autowired
    private SecKillGoodsMapper secKillGoodsMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 秒杀商品存入redis的定时任务
     */
    @Scheduled(cron = "0/15 * * * * *")
    public void seckillIntoRedisTask(){
        // 计算时间段：5个
        List<Date> dateMenus = DateUtil.getDateMenus();
        for (Date dateMenu : dateMenus) {
            // 从数据库查询对应时间段的商品数据
            // 计算时间段的截止时间
            String startTime = DateUtil.data2str(dateMenu, DateUtil.PATTERN_YYYY_MM_DDHHMM);
            // 计算时间段的截止时间
            Date date = DateUtil.addDateHour(dateMenu, 2);
            String endTime = DateUtil.data2str(date, DateUtil.PATTERN_YYYY_MM_DDHHMM);

            // 构建查询条件
            LambdaQueryWrapper<SeckillGoods> wrapper = new LambdaQueryWrapper<>();
            // 拼接查询条件
            // 审核状态必须是通过的
            wrapper.eq(SeckillGoods::getStatus,"1");
            // 剩余库存大于0
            wrapper.gt(SeckillGoods::getStockCount,0);
            // startTime =< 开始时间 结束时间 < endTime
            wrapper.ge(SeckillGoods::getStartTime,startTime);
            wrapper.le(SeckillGoods::getEndTime,endTime);

            String key = DateUtil.data2str(dateMenu, DateUtil.PATTERN_YYYYMMDDHH);
            Set keys = redisTemplate.boundHashOps(RedisConst.SECKILL_GOODS + ":" + key).keys();
            if(keys != null && keys.size() > 0){
                wrapper.notIn(SeckillGoods::getId,keys);
            }
            //查询数据库的数据
            List<SeckillGoods> seckillGoods = secKillGoodsMapper.selectList(wrapper);
            //存入Redis
            for (SeckillGoods seckillGood : seckillGoods) {
                redisTemplate.boundHashOps(RedisConst.SECKILL_GOODS + ":" + key).put(seckillGood.getId(), seckillGood);
            }

        }

    }
}
